import logging
from pathlib import Path
import re
from typing import Dict, List, Optional
from dataclasses import dataclass, field

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

@dataclass
class Bookmark:
    """书签数据类"""
    title: str
    url: str
    add_date: str = ""
    icon: str = ""

@dataclass 
class Category:
    """分类数据类"""
    name: str
    bookmarks: List[Bookmark] = field(default_factory=list)
    subcategories: Dict[str, 'Category'] = field(default_factory=dict)
    add_date: str = ""
    
class BookmarkParser:
    """书签解析器"""
    
    def __init__(self):
        self.root_category = Category("书签导航")
        logging.basicConfig(level=logging.INFO)
        self.logger = logging.getLogger(__name__)
        
    def parse(self, html_content: str) -> Category:
        """解析书签HTML文件并返回Category对象
        
        Args:
            html_content: HTML文件内容
            
        Returns:
            Category: 解析后的书签分类结构
        """
        self.logger.info("开始解析书签文件")
        return self._parse_with_regex(html_content)

    def _parse_with_regex(self, html_content: str) -> Category:
        """使用正则表达式解析书签
        
        Args:
            html_content: HTML文件内容
            
        Returns:
            Category: 解析后的书签分类结构
        """
        self.logger.info("开始使用正则表达式解析")
        
        
        
        # 查找所有分类(H3标签)和其内容，排除书签工具栏
        category_pattern = r'<DT><H3(?!.*PERSONAL_TOOLBAR_FOLDER="true")[^>]*>(.*?)</H3>\s*<DL[^>]*>(.*?)</DL>'
        categories = re.finditer(category_pattern, html_content, re.IGNORECASE | re.DOTALL)
        
        root_pattern = r'</DL><p>\s*(?:<DT><A\s+[^>]*HREF="([^"]+)"\s+[^>]*>([^<]+)</A>\s*)+</DL><p>\s*</DL><p>'
        root_match = re.search(root_pattern, html_content, re.IGNORECASE | re.DOTALL)
        logger.info(f"root_match: {root_match}")

        if root_match:
            # 创建根目录分类
            root_dir_category = Category("根目录")
            self.root_category.subcategories["根目录"] = root_dir_category
            # 解析根目录下的书签
            self._parse_root_bookmarks(root_match.group(0), root_dir_category)
            logger.info(f"已添加根目录书签到根目录文件夹")
        else:
            logger.info("没有找到根目录")
            
        for match in categories: 
            self.logger.info("-" * 50)  # 添加分隔线使输出更清晰
            category_name = match.group(1).strip()
            category_content = match.group(2)
            
            # 跳过书签栏
            # if 'PERSONAL_TOOLBAR_FOLDER' in match.group(0):
            #     self.logger.info(f"跳过书签栏: {category_name}")
            #     continue
                
            self.logger.info(f"找到分类: {category_name}")
            current_category = Category(category_name)
            
            # 解析分类下的书签
            self._parse_bookmarks(category_content, current_category)
            
            # 解析子分类
            self._parse_subcategories(category_content, current_category)
            
            # 添加到根分类
            self.root_category.subcategories[category_name] = current_category
            
        return self.root_category
    
    def _parse_bookmarks(self, content: str, category: Category):
        """解析书签
        
        Args:
            content: HTML内容
            category: 当前分类对象
        """
        # 解析书签
        bookmark_pattern = r'<DT><A[^>]*HREF="([^"]*)"[^>]*>(.*?)</A>'
        bookmarks = re.finditer(bookmark_pattern, content, re.IGNORECASE)
        
        for b_match in bookmarks:
            url = b_match.group(1)
            title = b_match.group(2).strip()
            
            # 提取add_date属性
            add_date = ''
            add_date_match = re.search(r'ADD_DATE="(\d+)"', b_match.group(0))
            if add_date_match:
                add_date = add_date_match.group(1)
                
            # 提取icon属性
            icon = ''
            icon_match = re.search(r'ICON="([^"]*)"', b_match.group(0))
            if icon_match:
                icon = icon_match.group(1)
                
            bookmark = Bookmark(title=title, url=url, add_date=add_date, icon=icon)
            # self.logger.info(f"添加书签: {bookmark.title}")
            category.bookmarks.append(bookmark)
            
    def _parse_subcategories(self, content: str, parent_category: Category):
        """解析子分类
        
        Args:
            content: HTML内容
            parent_category: 父分类对象
        """
        subcategory_pattern = r'<DT><H3[^>]*>(.*?)</H3>\s*<DL[^>]*>(.*?)</DL>'
        subcategories = re.finditer(subcategory_pattern, content, re.IGNORECASE | re.DOTALL)
        
        for match in subcategories:
            subcategory_name = match.group(1).strip()
            subcategory_content = match.group(2)
            
            self.logger.info(f"发现子分类: {subcategory_name}")
            subcategory = Category(subcategory_name)
            
            # 递归解析子分类的内容
            self._parse_bookmarks(subcategory_content, subcategory)
            self._parse_subcategories(subcategory_content, subcategory)
            
            # 添加到父分类
            parent_category.subcategories[subcategory_name] = subcategory
    
    def get_all_categories(self) -> List[Category]:
        """获取所有分类
        
        Returns:
            List[Category]: 分类列表
        """
        categories = []
        self._collect_categories(self.root_category, categories)
        return categories
    
    def _collect_categories(self, category: Category, result: List[Category]):
        """递归收集所有分类
        
        Args:
            category: 当前分类
            result: 结果列表
        """
        result.append(category)
        for subcategory in category.subcategories.values():
            self._collect_categories(subcategory, result)
            
    def get_category(self, name: str) -> Optional[Category]:
        """根据名称获取分类
        
        Args:
            name: 分类名称
            
        Returns:
            Category: 分类对象,未找到返回None
        """
        categories = self.get_all_categories()
        for category in categories:
            if category.name == name:
                return category
        return None 

    def _parse_root_bookmarks(self, content: str, category: Category):
        """解析根目录下的书签
        
        Args:
            content: 根目录HTML内容
            category: 根目录分类对象
        """
        # 解析根目录下的书签
        bookmark_pattern = r'<DT><A[^>]*HREF="([^"]*)"[^>]*>(.*?)</A>'
        bookmarks = re.finditer(bookmark_pattern, content, re.IGNORECASE)
        
        for b_match in bookmarks:
            url = b_match.group(1)
            title = b_match.group(2).strip()
            
            # 提取add_date属性
            add_date = ''
            add_date_match = re.search(r'ADD_DATE="(\d+)"', b_match.group(0))
            if add_date_match:
                add_date = add_date_match.group(1)
                
            # 提取icon属性
            icon = ''
            icon_match = re.search(r'ICON="([^"]*)"', b_match.group(0))
            if icon_match:
                icon = icon_match.group(1)
                
            bookmark = Bookmark(title=title, url=url, add_date=add_date, icon=icon)
            self.logger.info(f"添加根目录书签: {bookmark.title}")
            category.bookmarks.append(bookmark) 